package app.client;

import java.io.*;
import java.net.Socket;

/**
 * Created by IntelliJ IDEA.
 * User: Awake
 * Date: 25.03.12
 * Time: 16:39
 * To change this template use File | Settings | File Templates.
 */
public class ServiceClient implements Runnable {

    private static final String HOST = "127.0.0.1";
    private static final int PORT = 8189;
    PrintWriter out;
    Socket socket;
    Thread getMessagesThread;

    public ServiceClient() {
        try {
            socket = new Socket(HOST, PORT);
            out = new PrintWriter(new OutputStreamWriter(socket.getOutputStream()), true);
            getMessagesThread = new Thread(this);
            getMessagesThread.start();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public void sendMessage(String message) {
        out.println(message);
    }

    @Override
    public void run() {
        try {
            BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
            while (true) {
                String str;
                if ((str = in.readLine()) != null) {
                    RequestHandler.receive(str);
                    System.out.println(str);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void kill() {
        getMessagesThread.stop();
    }
}

